package com.wx.jwt.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wx
 * @Description: jwt认证过滤器
 * @date 2018/11/27 002711:20
 */
public class JwtFilter implements Filter {
    public final static String token = "token";
    /**
     * 这个密钥只有服务器才知道
     */
    public final static String secret = "secretkey";

    /**
     * @param filterConfig
     * @description: 容器在创建当前过滤器的时候自动调用
     * @author: wx
     * @date: 2018/11/27 0027
     * @return: void
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @description: 每次客户端请求都会调用一次。
     * @author: wx
     * @date: 2018/11/27 0027
     * @return: void
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        final String jwtToken = request.getHeader(token);
        if (StringUtils.isEmpty(jwtToken)) {
            throw new ServletException("jwtToken is null");
        }
        try {
            final Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(jwtToken).getBody();
            //System.out.println(claims.toString());
            request.setAttribute("claims", claims);
        } catch (final SignatureException e) {
            throw new ServletException("Invalid jwtToken");
        }

        filterChain.doFilter(request, response);
    }

    /**
     * @param
     * @description: 容器在销毁当前过滤器的时候自动调用
     * @author: wx
     * @date: 2018/11/27 0027
     * @return: void
     */
    @Override
    public void destroy() {

    }
}
